/*
 * Copyright (C) 2008
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.sca4idea.references;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceProvider;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ProcessingContext;
import com.googlecode.sca4idea.facet.SCAFacet;
import com.googlecode.sca4idea.providers.SCAComponentImplementation;
import com.googlecode.sca4idea.providers.SCAProvider;
import org.jetbrains.annotations.NotNull;

/**
 * ReferenceProvider used for all attributes in &lt;implementation.*&gt; tags.
 */
public class ImplementationReferenceProvider extends PsiReferenceProvider {
    private static final PsiReference[] EMPTY_REFERENCES = new PsiReference[0];

    @NotNull
    public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement,
                                                 @NotNull ProcessingContext processingContext) {
        // Retrieve the SCA Provider relevant to the element
        SCAProvider provider = SCAFacet.getProviderForElement(psiElement);
        if (provider == null) return EMPTY_REFERENCES;

        // Attempt to find an implementation for the tag
        XmlAttributeValue attrVal = (XmlAttributeValue) psiElement;
        XmlAttribute attr = (XmlAttribute) psiElement.getParent();
        XmlTag tag = attr.getParent();
        SCAComponentImplementation implementation = provider.getComponentImplementation(
                tag.getNamespace(), tag.getLocalName());
        if (implementation == null) return EMPTY_REFERENCES;

        PsiReferenceProvider attrProvider = implementation.getReferenceProvider(attr.getName(), attrVal);
        if (attrProvider == null) return EMPTY_REFERENCES;

        return attrProvider.getReferencesByElement(psiElement, processingContext);
    }
}
